package com.uetoken.cn.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.EncodeUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.popup.QMUIListPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.uetoken.cn.MainActivity;
import com.uetoken.cn.R;
import com.uetoken.cn.base.BaseActivity;
import com.uetoken.cn.common.Constant;
import com.uetoken.cn.utils.PickPhotoUtil;
import com.uetoken.cn.view.X5WebView;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.teahcourse.baseutil.GetPathFromUri4kitkat;

/**
 * 网页加载
 */
public class WebActivity extends BaseActivity {

    @BindView(R.id.activity_web_back)
    ImageView mIvBack;
    @BindView(R.id.activity_web_title)
    TextView mTvTitle;
    @BindView(R.id.iv_activity_web_close)
    ImageView mIvClose;
    @BindView(R.id.iv_activity_web_more)
    ImageView mIvMore;
    @BindView(R.id.activity_web_pb)
    ProgressBar mPb;
    @BindView(R.id.activity_web_webView)
    X5WebView webView;

    private ValueCallback<Uri> uploadMessage;
    private ValueCallback<Uri[]> uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    private String currentUrl;
    private String flag;
    private String[] moreStr = new String[2];
    /**
     * 记录title和标题
     */
    private Map<String, String> titles = new HashMap<>();
    private QMUIListPopup mListPopup;

    @Override
    public int getLayoutId() {
        return R.layout.activity_web;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        //状态栏沉浸式
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this, android.R.color.white), true);
        BarUtils.setStatusBarLightMode(this, true);
        getWindow().getDecorView().addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                ArrayList<View> outView = new ArrayList<View>();
                getWindow().getDecorView().findViewsWithText(outView, "QQ浏览器", View.FIND_VIEWS_WITH_TEXT);
                int size = outView.size();
                if (outView != null && outView.size() > 0) {
                    outView.get(0).setVisibility(View.GONE);
                }
            }
        });
        mPb.setMax(100);

    }

    @Override
    public void initData() {
        currentUrl = getIntent().getStringExtra(Constant.TO_WEBVIEW_URL);
        flag = getIntent().getStringExtra("flag");
        initPopup();
        initWebView();
        initPermissionForCamera();
    }

    @Override
    public void init() {

    }

    /**
     * Android 6.0以上版本，需求添加运行时权限申请；否则，可能程序崩溃
     */
    private static final int REQUEST_CODE_PERMISSION = 0x110;

    private void initPermissionForCamera() {
        int flag = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
        if (PackageManager.PERMISSION_GRANTED != flag) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (REQUEST_CODE_PERMISSION == requestCode) {
            switch (grantResults[0]) {
                case PackageManager.PERMISSION_DENIED:
                    boolean isSecondRequest = ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA);
                    if (isSecondRequest)
                        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSION);
                    else
                        Toast.makeText(this, "拍照权限被禁用，请在权限管理修改", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    }

    /**
     * 初始化webview
     */
    private void initWebView() {
        // 添加js对象(必要)
        webView.addJavascriptInterface(new UETWebInteration(this), "UETWebInteration");
        webView.clearCache(true);
        webView.setInitialScale(25);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                // mTestHandler.sendEmptyMessage(MSG_OPEN_TEST_URL);
                mTestHandler.sendEmptyMessageDelayed(MSG_OPEN_TEST_URL, 5000);// 5s?
                /* mWebView.showLog("test Log"); */
            }
        });
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new ChromeClient(new PickPhotoUtil(this)));
//        webView.setWebViewClient(new WebViewClient(){
//
//            @Override
//            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
//                view.loadUrl(request.getUrl().toString());
//                return true;
//            }
//
//            @Override
//            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//                super.onReceivedError(view, request, error);
//            }
//
//            @Override
//            public void onPageStarted(WebView view, String url, Bitmap favicon) {
//                super.onPageStarted(view, url, favicon);
//                currentUrl = url;
//            }
//
//            @Override
//            public void onPageFinished(WebView view, String url) {
//                super.onPageFinished(view, url);
//                String title = titles.get(url);
//                if (!TextUtils.isEmpty(title)){
//                    mTvTitle.setText(title);
//                }
//
//            }
//        });

        // 点击后退按钮,让WebView后退一页(也可以覆写Activity的onKeyDown方法)
        webView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (event.getAction() == KeyEvent.ACTION_DOWN) {
                    // 表示按返回键时的操作
                    if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
                        // 后退
                        webView.goBack();
                        // 已处理
                        return true;
                    }
                }
                return false;
            }
        });
        webView.loadUrl(currentUrl);

        WebSettings setting = webView.getSettings();
        WebSettings webSetting = webView.getSettings();
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);//设置支持缩放
        setting.setDisplayZoomControls(false);//是否使用内置的缩放机制
        webSetting.setUseWideViewPort(true);//设置此属性，可任意比例缩放
        webSetting.setSupportMultipleWindows(false);//是否支持多窗口
        webSetting.setLoadWithOverviewMode(true);// 缩放至屏幕的大小
        webSetting.setAppCacheEnabled(true);
        // 解决图片不显示
        setting.setBlockNetworkImage(false);//是否禁止从网络（通过http和https URI schemes访问的资源）下载图片资源，默认值为false
        // webSetting.setDatabaseEnabled(true);
        setting.setAllowContentAccess(true); // 是否可访问Content Provider的资源，默认值 true
        setting.setAllowFileAccess(true);    // 是否可访问本地文件，默认值 true
        // 是否允许通过file url加载的Javascript读取本地文件，默认值 false
        setting.setAllowFileAccessFromFileURLs(false);
        // 是否允许通过file url加载的Javascript读取全部资源(包括文件,http,https)，默认值 false
        setting.setAllowUniversalAccessFromFileURLs(false);
        setting.setDefaultTextEncodingName("UTF-8");

        webSetting.setDomStorageEnabled(true);//DOM存储API是否可用，默认false。调用相机必加，去掉或为false会闪退
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(this.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(this.getDir("geolocation", 0)
                .getPath());
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        // webSetting.setPreFectch(true);
        webView.loadUrl(currentUrl);
        CookieSyncManager.createInstance(this);
        CookieSyncManager.getInstance().sync();
    }

    /**
     * 初始化更多弹窗
     */
    private void initPopup() {
        if (mListPopup == null) {

            moreStr[0] = getResources().getString(R.string.str_web_refresh);
            moreStr[1] = getResources().getString(R.string.str_external_browser_open);

            List<String> data = new ArrayList<>();

            Collections.addAll(data, moreStr);

            ArrayAdapter adapter = new ArrayAdapter<>(this, R.layout.simple_list_item, data);

            mListPopup = new QMUIListPopup(this, QMUIPopup.DIRECTION_BOTTOM, adapter);
            mListPopup.create(QMUIDisplayHelper.dp2px(this, 150), QMUIDisplayHelper.dp2px(this, 200), new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    mListPopup.dismiss();
                    switch (i) {
                        case 0:
                            //刷新当前页面
                            webView.reload();
                            break;
                        case 1:
                            try {
                                Uri uri = Uri.parse(currentUrl);
                                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                                startActivity(intent);
                            } catch (Exception e) {
                                LogUtils.e("webError", e.getMessage());
                            }
                            break;
                    }
                }
            });

        }
    }


    @OnClick({R.id.activity_web_back, R.id.iv_activity_web_close, R.id.iv_activity_web_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.activity_web_back:
                if (webView.canGoBack()) {
                    webView.goBack();
                } else {
                    if (ObjectUtils.equals(flag, "advertising")) {
                        Intent intent = new Intent(this, MainActivity.class);
                        startActivity(intent);
                    }
                    finish();
                }
                break;
            case R.id.iv_activity_web_close:
                if (ObjectUtils.equals(flag, "advertising")) {
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                }
                finish();
                break;
            case R.id.iv_activity_web_more:
                mListPopup.show(mIvMore);
                break;
        }
    }

    private static final String TAG = "MyWebChromeClient";

    class ChromeClient extends WebChromeClient {

        private PickPhotoUtil pickPhotoUtil;

        public ChromeClient(PickPhotoUtil pickPhotoUtil) {
            this.pickPhotoUtil = pickPhotoUtil;
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            if (newProgress == 100) {
                mPb.setVisibility(View.GONE);
            } else {
                mPb.setVisibility(View.VISIBLE);
                mPb.setProgress(newProgress);
            }
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (TextUtils.isEmpty(title)) {
                title = "";
            }
            mTvTitle.setText(title);
            titles.put(currentUrl, title);
        }

        /**
         * For Android < 3.0
         * 过时的方法：openFileChooser
         *
         * @param filePathCallback
         */
        public void openFileChooser(ValueCallback<Uri> filePathCallback) {
            pickPhotoUtil.openFileManager();
            uploadMessage = filePathCallback;
            PickPhotoUtil.mFilePathCallback4 = filePathCallback;
            Log.d(TAG, "openFileChooser1: 被调用几次？");
        }

        /**
         * For Android  >= 3.0
         * 过时的方法：openFileChooser
         *
         * @param filePathCallback
         * @param acceptType
         */
        public void openFileChooser(ValueCallback filePathCallback, String acceptType) {
            pickPhotoUtil.promptDialog();
            uploadMessage = filePathCallback;
            String title = acceptType;
            PickPhotoUtil.mFilePathCallback4 = filePathCallback;
        }

        /**
         * For Android  >= 4.1
         * 过时的方法：openFileChooser
         *
         * @param filePathCallback
         * @param acceptType
         * @param capture
         */
        public void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
            pickPhotoUtil.promptDialog();
            uploadMessage = filePathCallback;
            String title = acceptType;
            PickPhotoUtil.mFilePathCallback4 = filePathCallback;
        }

        /**
         * For Android >= 5.0
         *
         * @param webView
         * @param filePathCallback
         * @param fileChooserParams
         * @return
         */
        @Override
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
            super.onShowFileChooser(webView, filePathCallback, fileChooserParams);
            uploadMessageAboveL = filePathCallback;
            pickPhotoUtil.promptDialog();
            PickPhotoUtil.mFilePathCallback = filePathCallback;
            Log.d(TAG, "onShowFileChooser2: 被调用几次？");
            /**
             * 返回true，如果filePathCallback被调用；返回false，如果忽略处理
             */

            return true;
        }
    }

    private void openImageChooserActivity() {

        AndPermission.with(this).runtime().permission(Permission.Group.CAMERA, Permission.Group.STORAGE).onGranted(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "Image Chooser"), FILE_CHOOSER_RESULT_CODE);
            }
        }).onDenied(new Action<List<String>>() {
            @Override
            public void onAction(List<String> data) {
                ToastUtils.showShort(getResources().getString(R.string.str_camera_not_use));
            }
        }).start();

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null) {
            return;
        }
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null) {
                    results = new Uri[]{Uri.parse(dataString)};
                }

            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (webView != null && webView.canGoBack()) {
                webView.goBack();
                return true;
            } else {
                if (ObjectUtils.equals(flag, "advertising")) {
                    Intent intent = new Intent(this, MainActivity.class);
                    startActivity(intent);
                }
                return super.onKeyDown(keyCode, event);
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**
         * 处理页面返回或取消选择结果
         */
        switch (requestCode) {
            case PickPhotoUtil.REQUEST_FILE_PICKER:
                pickPhotoResult(resultCode, data);
                break;
            case PickPhotoUtil.REQUEST_CODE_PICK_PHOTO:
                pickPhotoResult(resultCode, data);
                break;
            case PickPhotoUtil.REQUEST_CODE_TAKE_PHOTO:
                takePhotoResult(resultCode);
                break;
            case PickPhotoUtil.REQUEST_CODE_PREVIEW_PHOTO:
                cancelFilePathCallback();
                break;
            case FILE_CHOOSER_RESULT_CODE:
                if (null == uploadMessage && null == uploadMessageAboveL) {
                    return;
                }
                Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
                if (uploadMessageAboveL != null) {
                    onActivityResultAboveL(requestCode, resultCode, data);
                } else if (uploadMessage != null) {
                    uploadMessage.onReceiveValue(result);
                    uploadMessage = null;
                }
                break;
            default:
                break;
        }
    }

    private void pickPhotoResult(int resultCode, Intent data) {
        if (PickPhotoUtil.mFilePathCallback != null) {
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result != null) {
                String path = GetPathFromUri4kitkat.getPath(this, result);
                Uri uri = Uri.fromFile(new File(path));
                PickPhotoUtil.mFilePathCallback.onReceiveValue(new Uri[]{uri});
                /**
                 * 将路径赋值给常量photoFile4，记录第一张上传照片路径
                 */
                PickPhotoUtil.photoPath = path;

                Log.d(TAG, "onActivityResult3: " + path);
            } else {
                /**
                 * 点击了file按钮，必须有一个返回值，否则会卡死
                 */
                PickPhotoUtil.mFilePathCallback.onReceiveValue(null);
                PickPhotoUtil.mFilePathCallback = null;
            }
            /**
             * 针对API 19之前的版本
             */
        } else if (PickPhotoUtil.mFilePathCallback4 != null) {
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (result != null) {
                String path = GetPathFromUri4kitkat.getPath(this, result);
                Uri uri = Uri.fromFile(new File(path));
                PickPhotoUtil.mFilePathCallback4.onReceiveValue(uri);
                /**
                 * 将路径赋值给常量photoFile
                 */
                Log.d(TAG, "onActivityResult4: " + path);
            } else {
                /**
                 * 点击了file按钮，必须有一个返回值，否则会卡死
                 */
                PickPhotoUtil.mFilePathCallback4.onReceiveValue(null);
                PickPhotoUtil.mFilePathCallback4 = null;
            }
        }
    }

    private void takePhotoResult(int resultCode) {
        if (PickPhotoUtil.mFilePathCallback != null) {
            if (resultCode == RESULT_OK) {
                String path = PickPhotoUtil.photoPath;
                Uri uri = Uri.fromFile(new File(path));
                PickPhotoUtil.mFilePathCallback.onReceiveValue(new Uri[]{uri});

                Log.d(TAG, "onActivityResult5: " + path);
            } else {
                /**
                 * 点击了file按钮，必须有一个返回值，否则会卡死
                 */
                PickPhotoUtil.mFilePathCallback.onReceiveValue(null);
                PickPhotoUtil.mFilePathCallback = null;
            }
            /**
             * 针对API 19之前的版本
             */
        } else if (PickPhotoUtil.mFilePathCallback4 != null) {
            if (resultCode == RESULT_OK) {
                String path = PickPhotoUtil.photoPath;
                Uri uri = Uri.fromFile(new File(path));
                PickPhotoUtil.mFilePathCallback4.onReceiveValue(uri);

                Log.d(TAG, "onActivityResult6: " + path);
            } else {
                /**
                 * 点击了file按钮，必须有一个返回值，否则会卡死
                 */
                PickPhotoUtil.mFilePathCallback4.onReceiveValue(null);
                PickPhotoUtil.mFilePathCallback4 = null;
            }
        }
    }

    private void cancelFilePathCallback() {
        if (PickPhotoUtil.mFilePathCallback4 != null) {
            PickPhotoUtil.mFilePathCallback4.onReceiveValue(null);
            PickPhotoUtil.mFilePathCallback4 = null;
        } else if (PickPhotoUtil.mFilePathCallback != null) {
            PickPhotoUtil.mFilePathCallback.onReceiveValue(null);
            PickPhotoUtil.mFilePathCallback = null;
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent == null || webView == null || intent.getData() == null)
            return;
        webView.loadUrl(intent.getData().toString());
    }

    @Override
    protected void onDestroy() {
        if (mTestHandler != null)
            mTestHandler.removeCallbacksAndMessages(null);
        if (webView != null)
            webView.destroy();
        super.onDestroy();
    }


    class UETWebInteration {
        Activity activity;

        public UETWebInteration(Activity activity) {
            this.activity = activity;
        }

        @JavascriptInterface
        public void jsTunedupNativeWithTypeParamSign(int type, String json, String encryption) {
            LogUtils.dTag("jsTunedupNativeWithTypeParamSign", "type = " + type + " json = " + json + " encryption = " + encryption);
            if (type == Constant.JS_WEB_TITLE) {
//                {"title":"新标题"}
                if (!ObjectUtils.isEmpty(json)) {
                    String titleJson = new String(EncodeUtils.base64Decode(json.getBytes()));
                    LogUtils.dTag("jsTunedupNativeWithTypeParamSign", "titleJson = " + titleJson);
                    JSONObject jsonObject = null;
                    try {
                        if (!ObjectUtils.isEmpty(titleJson)) {
                            jsonObject = new JSONObject(titleJson);
                            String title = jsonObject.getString("title");
                            if (!ObjectUtils.isEmpty(title)) {
                                mTvTitle.setText(title);
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

        }
    }

    public static final int MSG_OPEN_TEST_URL = 0;
    public static final int MSG_INIT_UI = 1;
    private final int mUrlStartNum = 0;
    private int mCurrentUrl = mUrlStartNum;
    private Handler mTestHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_OPEN_TEST_URL:
                    String url = "file:///sdcard/outputHtml/html/"
                            + Integer.toString(mCurrentUrl) + ".html";
                    if (webView != null) {
                        webView.loadUrl(url);
                    }
                    mCurrentUrl++;
                    break;
                case MSG_INIT_UI:
//                    init();
                    break;
            }
            super.handleMessage(msg);
        }
    };

}
